﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PublicData;
using XinjeMesProgram.Entities;
using XinjeMesProgram.Entities.RoleAndUser;
using XinjeMesProgram.Entities.Permission;
using XinjeMesProgram.Entities.User;
using MesAPI.Extensions.AuthContext;
using Microsoft.EntityFrameworkCore;
using XinjeAuthService.Function;
using Microsoft.AspNetCore.Authorization;

namespace MesAPI.Controllers.UserAndRole
{
    /// <summary>
    /// 权限控制器.
    /// </summary>
    [Route("api/v1/rbac/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class PermissionController : ControllerBase
    {
        private ResponseModel retData = new();

        /// <summary>
        /// 获取某个角色的权限菜单树.
        /// </summary>
        /// <param name="code">角色编码.</param>
        /// <returns>角色权限.</returns>
        [HttpGet("{code}")]
        public ResponseModel Permission_tree(string code)
        {
            using var dbContext = new FactoryMesContext();
            {
                AuthRole roleEntity = dbContext.AuthRole.FirstOrDefault(x => x.Code == code);
                if (roleEntity != null)
                {
                    List<PermissionMenuTree> menuTree = dbContext.AuthMenu.Where(x => x.Status == CommonEnum.Status.Normal).OrderBy(x => x.Sort)
                        .Select(x => new PermissionMenuTree
                        {
                            Guid = x.Guid,
                            ParentGuid = x.ParentGuid,
                            Title = x.Name,
                        }).ToList();

                    string sql = string.Empty;
                    if (roleEntity.IsSuperAdministrator == 1)
                    {
                        sql = @"SELECT P.Code, P.MenuGuid, P.Name, P.ActionCode, 'SUPERADM' AS RoleCode, (CASE WHEN P.Code IS NOT NULL THEN 1 ELSE 0 END) AS IsAssigned 
                            FROM AuthPermission AS P WHERE P.Status = 1";
                    }
                    else
                    {
                        sql = @"SELECT P.Code, P.MenuGuid, P.Name, P.ActionCode, IsNull(S.RoleCode,'') AS RoleCode, (CASE WHEN S.PermissionCode IS NOT NULL THEN 1 ELSE 0 END) AS IsAssigned 
                            FROM AuthPermission AS P LEFT JOIN (SELECT * FROM authRolePermissionMapping AS RPM WHERE RPM.RoleCode = {0}) AS S ON S.PermissionCode= P.Code";

                        if (AuthContextService.CurrentUser.UserType != UserType.SuperAdministator)
                        {
                            string thisOptRoleCode = AuthContextService.CurrentUser.RoleCode;
                            List<PermissionWithAssignProperty> thisOptRolePermissionList = dbContext.PermissionWithAssignProperty.FromSqlRaw(sql, thisOptRoleCode).ToList();
                            List<PermissionMenuTree> newMenuListTemp = new();
                            menuTree.FilterMenuList(thisOptRolePermissionList, "400000", ref newMenuListTemp);
                            menuTree = newMenuListTemp;
                        }
                    }

                    List<PermissionWithAssignProperty> permissionList = dbContext.PermissionWithAssignProperty.FromSqlRaw(sql, code).ToList();
                    var tree = menuTree.FillRecursive(permissionList, "400000", Convert.ToBoolean(roleEntity.IsSuperAdministrator));
                    this.retData.SetData(new { tree, selectedPermissions = permissionList.Where(x => x.IsAssigned == 1).Select(x => x.Code) });
                }
                else
                {
                    this.retData.SetFailed("角色不存在");
                }
            }

            return this.retData;
        }
    }
}
